package com.jch.dm3.exercise;

public class GracefulThread extends Thread{

    /**
     * 发出请求后变为true
     */
    private volatile boolean shutdownRequested = false;

    /**
     * 终止请求
     */
    public final void shutdownRequest(){
        shutdownRequested = true;
        interrupt();
    }

    /**
     * 检查是否已经发出了终止请求
     * @return shutdownRequested
     */
    public final boolean isShutdownRequested(){
        return shutdownRequested;
    }

    @Override
    public void run() {
        try{
            while(!isShutdownRequested()) {
                doWork();
            }
        }catch(InterruptedException e){
        }finally{
            doShutdown();
        }
    }

    // 操作
    protected void doWork() throws InterruptedException{
    }

    protected void doShutdown(){

    }
}
